package com.ct.gd.passport.view.passport;

import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.ksoap2.serialization.SoapObject;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

import com.ct.gd.passport.R;
import com.ct.gd.passport.common.BaseActivity;
import com.ct.gd.passport.common.constants.Config;
import com.ct.gd.passport.common.constants.Protocol;
import com.ct.gd.passport.common.constants.UmengVar;
import com.ct.gd.passport.common.webservice.WebServiceUtil;
import com.ct.gd.passport.domain.PassportReservation;
import com.ct.gd.passport.view.widget.CustomHeaderFragment;
import com.umeng.analytics.MobclickAgent;
import com.up91.common.android.async.ILoading;
import com.up91.common.android.async.SimpleAsyncTask;
import com.up91.common.android.helper.L;
import com.up91.common.android.helper.ToastHelper;

public class PassportWeekendReservationActivity extends BaseActivity implements OnClickListener, OnItemSelectedListener {
	private static final int START_TIME = 1;
	private static final int END_TIME = 2;
	private static final String PATTERN = "%d-%02d-%d";

	private Spinner mSpPlace;
	private Spinner mSpDate;
	private Spinner mSpBizType;
	private Spinner mSpHouseholdAddr;
	private EditText mEtPerson;
	private EditText mEtPhone;

	private Button mBtnStartTime;
	private Button mBtnEndTime;
	private Button mBtnSubmit;

	private int mPlace = -1;
	private String mDate = "";
	private int mBizType = -1;
	private int mHouseholdAddr = -1;

	private int mCurrYear;
	private int mCurrMonth;
	private int mCurrDay;

	private int mStartYear;
	private int mEndYear;
	private int mStartMonth;
	private int mEndMonth;
	private int mStartDay;
	private int mEndDay;
	private String mStartTime;
	private String mEndTime;

	private boolean mHasInfo = false;

	private DatePickerDialog.OnDateSetListener mStartDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mStartYear = year;
			mStartMonth = monthOfYear;
			mStartDay = dayOfMonth;
			mStartTime = String.format(PATTERN, mStartYear, mStartMonth + 1, mStartDay);
			mBtnStartTime.setText(mStartTime);
		}
	};

	private DatePickerDialog.OnDateSetListener mEndDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mEndYear = year;
			mEndMonth = monthOfYear;
			mEndDay = dayOfMonth;
			mEndTime = String.format(PATTERN, mEndYear, mEndMonth + 1, mEndDay);
			mBtnEndTime.setText(mEndTime);
		}
	};

	@Override
	protected void onBaseCreate(Bundle savedInstanceState) {
		setContentView(R.layout.immgration_form);
	}

	@Override
	protected void initViews() {
		CustomHeaderFragment header = (CustomHeaderFragment) getFragmentManager().findFragmentById(R.id.header);
		header.setCenterText(R.string.passport_submit_weekend);

		mSpPlace = (Spinner) findViewById(R.id.immigration_place_spin);
		mSpDate = (Spinner) findViewById(R.id.immigration_date_spin);
		mSpBizType = (Spinner) findViewById(R.id.immigration_busi_spin);
		mSpHouseholdAddr = (Spinner) findViewById(R.id.immigration_hk_place_spin);
		mSpPlace.setOnItemSelectedListener(this);
		mSpDate.setOnItemSelectedListener(this);
		mSpBizType.setOnItemSelectedListener(this);
		mSpHouseholdAddr.setOnItemSelectedListener(this);

		mBtnStartTime = (Button) findViewById(R.id.immigration_date_begin);
		mBtnEndTime = (Button) findViewById(R.id.immigration_date_end);
		mBtnStartTime.setOnClickListener(this);
		mBtnEndTime.setOnClickListener(this);

		mEtPerson = (EditText) findViewById(R.id.edt_immigration_person);
		mEtPhone = (EditText) findViewById(R.id.edt_immigration_phone);

		mBtnSubmit = (Button) findViewById(R.id.btn_immigration_submit);
		mBtnSubmit.setOnClickListener(this);

		new LoadInfoTask(this, true).execute();
	}

	@Override
	protected void setFieldValues() {
		Calendar c = Calendar.getInstance();
		mStartYear = mEndYear = mCurrYear = c.get(Calendar.YEAR);
		mStartMonth = mEndMonth = mCurrMonth = c.get(Calendar.MONTH);
		mStartDay = mEndDay = mCurrDay = c.get(Calendar.DAY_OF_MONTH);
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case START_TIME:
			return new DatePickerDialog(this, mStartDateSetListener, mStartYear, mStartMonth, mStartDay);
		case END_TIME:
			return new DatePickerDialog(this, mEndDateSetListener, mEndYear, mEndMonth, mEndDay);
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
		switch (id) {
		case START_TIME:
			((DatePickerDialog) dialog).updateDate(mStartYear, mStartMonth, mStartDay);
			break;
		case END_TIME:
			((DatePickerDialog) dialog).updateDate(mEndYear, mEndMonth, mEndDay);
			break;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		switch (parent.getId()) {
		case R.id.immigration_place_spin:
			// mPlace = getResources().getIntArray(R.array.immigration_place_type_values)[position];
			if (mCrDepListIds != null) {
				mPlace = mCrDepListIds[position];
			}
			break;
		case R.id.immigration_date_spin:
			if (mCrDateList != null) {
				mDate = mCrDateList[position];
			}
			break;
		case R.id.immigration_busi_spin:
			if (mCrTypeIds != null) {
				mBizType = mCrTypeIds[position];
			}
			//			mBizType = getResources().getIntArray(R.array.immigration_busi_type_values)[position];
			break;
		case R.id.immigration_hk_place_spin:
			mHouseholdAddr = getResources().getIntArray(R.array.GRLY_AREAS_INT_VALUE)[position];
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.immigration_date_begin:
			showDialog(START_TIME);
			break;
		case R.id.immigration_date_end:
			showDialog(END_TIME);
			break;
		case R.id.btn_immigration_submit:
			if(mHasInfo){
				MobclickAgent.onEvent(this, UmengVar.PASSPORT_IMMI_SUBMIT);
				submit();
			}else{
				showNoServiceAlert();
			}
			break;
		}
	}

	private void submit() {
		try {
			PassportReservation reservation = genReservation();
			new SubmitTask((ILoading) this, true).execute(reservation);
		} catch (IllegalArgumentException e) {
			ToastHelper.toast(this, e.getMessage());
			return;
		}
	}

	private void showNoServiceAlert() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(PassportWeekendReservationActivity.this).setTitle(R.string.failure)
				.setMessage("暂无预约服务！").setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						PassportWeekendReservationActivity.this.finish();
					};
				});
		dialog.show();
	}

	/**
	 * @return 是否前者(this)时间大于(that)后者
	 */
	private boolean compareTime(int thisYear, int thisMonth, int thisDay, int thatYear, int thatMonth, int thatDay) {
		return thisYear > thatYear || ((thisYear == thatYear) && (thisMonth > thatMonth))
				|| ((thisYear == thatYear) && (thisMonth == thatMonth) && (thisDay > thatDay));
	}

	private PassportReservation genReservation() throws IllegalArgumentException {
		//		if (StringUtils.isEmpty(mStartTime))
		//			throw new IllegalArgumentException("请选择预约开始日期");
		//		if (StringUtils.isEmpty(mEndTime))
		//			throw new IllegalArgumentException("请选择预约结束日期");
		//		if (compareTime(mCurrYear, mCurrMonth, mCurrDay, mStartYear, mStartMonth, mStartDay))
		//			throw new IllegalArgumentException("预约开始日期过早");
		//		if (compareTime(mStartYear, mStartMonth, mStartDay, mEndYear, mEndMonth, mEndDay))
		//			throw new IllegalArgumentException("开始预约日期须在结束日期之前");
		// if (mStartYear > mEndYear || ((mStartYear == mEndYear) &&
		// (mStartMonth > mEndMonth))
		// || ((mStartYear == mEndYear) && (mStartMonth == mEndMonth) &&
		// (mStartDay > mEndDay))) throw new IllegalArgumentException(
		// "开始预约日期不能在结束日期之后");
		String person = mEtPerson.getEditableText().toString();
		String phone = mEtPhone.getEditableText().toString();
		if (StringUtils.isBlank(person))
			throw new IllegalArgumentException("请填写预约人");
		if (StringUtils.isBlank(phone))
			throw new IllegalArgumentException("请填写联系电话");
		mDate = mSpDate.getSelectedItem().toString();
		if (StringUtils.isEmpty(mDate)) {
			throw new IllegalArgumentException("请填写预约日期");
		}

		return new PassportReservation(mPlace, mDate, mStartTime, mEndTime, person, phone, mBizType, mHouseholdAddr);
	}

	private int[] mCrDepListIds;
	private String[] mCrDepListNames;

	private String[] mCrDateList;

	private int[] mCrTypeIds;
	private String[] mCrTypeNames;

	@SuppressWarnings("rawtypes")
	private class LoadInfoTask extends SimpleAsyncTask<Void, Void, Boolean> {

		//		private final String targetNameSpace = "http://119.145.141.231/soap/bookCrj/";
		//		private final String WSDL = "http://119.145.141.231:20105/webservice/fshb_crj.php";

		public LoadInfoTask(ILoading loading, boolean showLoading) {
			super(loading, showLoading);
		}

		@Override
		protected Boolean onLoad(Void... params) throws Exception {
			return getCrDepList() && getCrDateList() && getCrTypeList();
		}

		private boolean getCrDepList() {
			try {
				List list = (List) WebServiceUtil.callWebService(Config.WEBSERVICE_NAME_SPACE, Config.WEBSERVICE_WSDL,
						Protocol.Commands.WS_METHOD_GET_DEP_LIST);
				int size = list.size();
				mCrDepListIds = new int[size];
				mCrDepListNames = new String[size];
				for (int idx = 0; idx < size; idx++) {
					SoapObject sob = (SoapObject) list.get(idx);
					mCrDepListIds[idx] = (Integer) sob.getProperty("depid");
					mCrDepListNames[idx] = sob.getPropertyAsString("depname");
				}
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}

		private boolean getCrDateList() {
			try {
				List list = (List) WebServiceUtil.callWebService(Config.WEBSERVICE_NAME_SPACE, Config.WEBSERVICE_WSDL,
						Protocol.Commands.WS_METHOD_GET_DATE_LIST);
				L.i("list::::", list.toString());
				int size = list.size();
				mCrDateList = new String[size];
				for (int idx = 0; idx < size; idx++) {
					SoapObject sob = (SoapObject) list.get(idx);
					mCrDateList[idx] = sob.getPropertyAsString("crdate");
					L.i("mCrDateList:", mCrDateList[idx]);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}

		private boolean getCrTypeList() {
			try {
				List list = (List) WebServiceUtil.callWebService(Config.WEBSERVICE_NAME_SPACE, Config.WEBSERVICE_WSDL,
						Protocol.Commands.WS_METHOD_GET_BIZ_TYPE_LIST);
				int size = list.size();
				mCrTypeIds = new int[size];
				mCrTypeNames = new String[size];
				for (int idx = 0; idx < size; idx++) {
					SoapObject sob = (SoapObject) list.get(idx);
					mCrTypeIds[idx] = (Integer) sob.getProperty("typeid");
					mCrTypeNames[idx] = sob.getPropertyAsString("typename");
					L.i("CrType:", mCrTypeIds[idx] + " " + mCrTypeNames[idx]);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}

		@Override
		protected void onUI(Boolean result) {
			PassportWeekendReservationActivity.this.mHasInfo = result;
			if (result) {
				setArrayAdapter(mSpPlace, mCrDepListNames);
				setArrayAdapter(mSpDate, mCrDateList);
				setArrayAdapter(mSpBizType, mCrTypeNames);
			} else {
				String[] arr = new String[] { "暂无" };
				setArrayAdapter(mSpPlace, arr);
				setArrayAdapter(mSpDate, arr);
				setArrayAdapter(mSpBizType, arr);
				PassportWeekendReservationActivity.this.showNoServiceAlert();
			}
		}

		private void setArrayAdapter(Spinner spr, String[] list) {
			ArrayAdapter adapter = new ArrayAdapter<String>(PassportWeekendReservationActivity.this, android.R.layout.simple_spinner_item, list);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spr.setAdapter(adapter);
		}

	}

	private class SubmitTask extends SimpleAsyncTask<PassportReservation, Void, String> {

		public SubmitTask(ILoading loading, boolean showLoading) {
			super(loading, showLoading);
		}

		@Override
		protected String onLoad(PassportReservation... params) throws Exception {
			return params[0].submit();
		}

		@Override
		protected void onUI(String result) {
			if (result.length() >= 12) {
				String info = getResources().getString(R.string.immigration_success);
				AlertDialog.Builder dialog = new AlertDialog.Builder(PassportWeekendReservationActivity.this).setTitle(R.string.success).setMessage(
						info + "\n预约工单号：" + result);
				dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						PassportWeekendReservationActivity.this.finish();
					}
				});
				dialog.show();
			} else {
				String msg = null;
				if (result.equals("4")) {
					msg = "预约日期值有误，请重新输入";
				} else if (result.equals("3")) {
					msg = "出入境局ID或业务类型ID数值有误";
				} else if (result.equals("2")) {
					msg = "有参数为空值";
				} else {
					msg = "预约失败，请重试";
				}
				AlertDialog.Builder dialog = new AlertDialog.Builder(PassportWeekendReservationActivity.this).setTitle(R.string.failure).setMessage(
						msg);
				dialog.show();
			}
			//			ToastHelper.toast(PassportWeekendReservationActivity.this, R.string.immigration_success);

		}
	}
}
